<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable implements MustVerifyEmail
{
    use HasApiTokens, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'username', 'email', 'password', 'avatar_url'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * 用户能力关系
     */
    public function abilities()
    {
        return $this->hasMany(UserAbility::class);
    }

    /**
     * 获取最新的能力数据
     */
    public function latestAbilities()
    {
        return $this->abilities()->latest()->first();
    }

    /**
     * 用户成就关系
     */
    public function achievements()
    {
        return $this->hasMany(UserAchievement::class);
    }

    /**
     * 用户统计关系
     */
    public function statistics()
    {
        return $this->hasOne(UserStatistic::class);
    }

    /**
     * 训练会话关系
     */
    public function trainingSessions()
    {
        return $this->hasMany(TrainingSession::class);
    }

    /**
     * 社区分享关系
     */
    public function communityShares()
    {
        return $this->hasMany(CommunityShare::class);
    }

    /**
     * 求助请求关系
     */
    public function helpRequests()
    {
        return $this->hasMany(HelpRequest::class);
    }

    /**
     * 用户通知关系
     */
    public function notifications()
    {
        return $this->hasMany(UserNotification::class);
    }

    /**
     * 用户段位关系
     */
    public function tiers()
    {
        return $this->hasMany(UserTier::class);
    }

    /**
     * 获取当前段位
     */
    public function currentTier()
    {
        return $this->tiers()->where('is_current', true)->first();
    }

    /**
     * 收藏的角色关系
     */
    public function favoriteCharacters()
    {
        return $this->belongsToMany(AiCharacter::class, 'user_character_favorites', 'user_id', 'character_id')
                    ->withTimestamps();
    }

    /**
     * 每日挑战关系
     */
    public function dailyChallenges()
    {
        return $this->belongsToMany(DailyChallenge::class, 'user_daily_challenges')
                    ->withPivot(['challenge_date', 'is_completed', 'completed_at', 'reward_earned']);
    }
}